package com.student.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.student.dao.StudentDao;
import com.student.entity.StudentInfo;

public class SingupServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public SingupServlet() {
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		StudentDao studao = new StudentDao();
		String stuNo = null ;
		String[] races = {"1000m长跑","400m短跑","立定跳远","铁人三项"};
		String race = null;
		String imageUrl ;
//点击报名获取学号，赛事，身份证图片地址。	
		boolean ismultipart = ServletFileUpload.isMultipartContent(request);
		if(ismultipart){
			System.out.println("设置了 entype=‘multipart/form-data’");
			
		DiskFileItemFactory	factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		//再通过parseRequest解析form中所以的请求字段，并保存到一个集合中
		try {
			List<FileItem> items = upload.parseRequest(request);
			
			//遍历items中的数据（stuNo races imagephoto）
			Iterator<FileItem> iterator = items.iterator();
			while(iterator.hasNext()){
				FileItem item = iterator.next();
		
			//判断前端字段是普通form 表单字段(stuNo races)，还是文件字段(imagephoto)
			if(item.isFormField()){
				//根据name的属性 判断item 是stuNo races 还是imagephoto
				if(item.getFieldName().equals("stuNo")){
					stuNo = item.getString("utf-8");

				}else if(item.getFieldName().equals("races")){
					String chose = item.getString("utf-8");
					
					for(int i=0;i<races.length;i++){
					race = races[i].equals(chose)?chose:null;
					}
		
			}else{
				//文件上传
				String fileName = item.getName();
	//判断文件格式的  .后缀
			String ext = fileName.substring((fileName.indexOf(".")));
			System.out.println(ext);
				if(ext.equals(".png")||ext.equals(".jpg")||ext.equals(".gif")){
				//获取文件内容 并且上传
				//定义文件路径；指定上传的位置(服务器的路径)imageUrl
				//动态获取相对路径
				imageUrl = request.getSession().getServletContext().getRealPath("imageUrl");
				System.out.println("获取动态路径地址"+imageUrl);
				File file = new File(imageUrl, fileName);
	
				item.write(file);   //上传
			System.out.println(fileName+"上传完成..");
			
			//将获得的学号，赛事，身份证图片地址
			StudentInfo stuInfo = new StudentInfo(stuNo, race, imageUrl);
			//将以上的信息添加到数据库
			studao.addStudent(stuInfo);
			
			
		
			//跳转到个人报名信息界面
			request.getRequestDispatcher("StudentInfoServlet").forward(request, response);
			
			PrintWriter out = response.getWriter();
			out.println("上传ok..");
				}else{System.out.println("文件格式不正确...");
					return;}
			}
		}
	
		}
		}catch(FileUploadBase.FileSizeLimitExceededException e){//为文件上传超过设置时异常处理
			e.printStackTrace();
		}catch (FileUploadException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
}
		
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
